package com.sl.au.repository;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import com.sl.au.entity.EventType;
import com.sl.au.entity.Part;

@Transactional(readOnly = true)
public interface PartRepository extends JpaRepository<Part, String> {

	@Query(" select a from Part a where a.partParent is not null order by a.partLevel.extended1 asc,a.partOrder asc")
	List<Part> findAllNodes();

	@Query(" select a from Part a where a.partParent is null and ( a.partName like %?1% or a.partIdentify like %?1% or a.partLevel.title like %?1%) ")
	Page<Part> getPartByKey(String key, Pageable pageable);

	@Query(" select count(*) from Part a where a.partParent is null and ( a.partName like %?1% or a.partIdentify like %?1% or a.partLevel.title like %?1%) ")
	long getPartByKeyCount(String key);

	@Query(" select a from Part a where a.partParent is null ")
	Page<Part> getPart(Pageable pageable);

	@Query(" select count(*) from Part a where a.partParent is null ")
	long getPartCount();

	@Modifying
	@Query("update Part a set a.partParent = null where a.id in (?1)")
	int setPart(String[] ids);

	@Query(" select IFNULL(max(a.partOrder),-2) + 2 from Part a where a.partParent = ?1 ")
	int getPartOrder(String parentId);

	@Query(" select a from Part a where a.partParent = ?1 order by a.partOrder asc")
	List<Part> getPartsByParent(String parentId);

	Part findTopByPartParentAndPartIdentify(String partParent, String partIdentify);

	Page<Part> findByPartParent(String partParent, Pageable pageable);

	@Query(" select a from Part a where a.partParent = ?1 and ( a.partName like %?2% or a.partIdentify like %?2% or a.partLevel.title like %?2%) ")
	Page<Part> findByPartParentAndKey(String id, String key, Pageable pageable);

	@Query("select a from Part a where a.partParent = ?1")
	List<Part> findByParentId(String parentId);

	@Query("select a from Part a where a.partName=?1")
	Part findByPartName(String name);
}
